--
-- Author: shunguo.chen
-- Date: 2018-01-09 15:22:23
--
-- CosplayModel

local CosplayRole = import(".CosplayRole")
local CosplayInfo = import(".CosplayInfo")
local CosplayChoice = import(".CosplayChoice")
local CosKOFInfo = import(".CosKOFInfo")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

function ClassRef:ctor(data)
	self.super.ctor(self, data)
end

function ClassRef:init()
    -- 所有可扮演角色
    self._roleDict = nil

    -- 当前扮演类型 nil（无） 1（普通cos） 2（kof）
    self._cosType = nil

    -- 普通角色扮演
    self._infos = nil
    self._roles = nil

    -- kof 角色扮演
    self._kofInfos = nil
    self._isInSelect = false

    self._kofMapId = GD:getTeamThirdTargetMapId(303)
end

function ClassRef:clear()
    self._cosType = nil
    self._infos = nil
    self._roles = nil

    self._kofInfos = nil
    self._isInSelect = false
end

function ClassRef:getKOFVSInfos()
    if not self._kofInfos then return nil end

    local myInfos = {}
    local enemyInfos = {}
    local names = {0, 0}
    for _,info in ipairs(self._kofInfos) do
        if info:isMyTeam() then
            for i,role in ipairs(info:getRoles()) do
                myInfos[#myInfos + 1] = role:getAvatarParams()
            end
            names[1] = info.baseInfo.name
        else
            for _,role in ipairs(info:getRoles()) do
                enemyInfos[#enemyInfos + 1] = role:getAvatarParams(true)
            end
            names[2] = info.baseInfo.name
        end
    end
    local infos = {myInfos, enemyInfos, names}
    return infos
end

function ClassRef:isKOFMap()
    local mapId = MapManager:getMapId()
    return mapId == self._kofMapId
end

function ClassRef:getRoles()
    return self._roles
end

-- 根据玩法id，获取可扮演的角色
function ClassRef:getRolesByPlayId(playId)
    if not playId then return end
    local conf = GD:queryCosplayTargetConf(playId)
    if not conf then return end

    local roles = {}
    local roleIds = table.tonumber(string.split(conf.rolePool, ";"))
    for _,id in ipairs(roleIds) do
        roles[#roles + 1] = self:getRoleById(id)
    end
    return roles
end

function ClassRef:getRoleById(id)
    if nil == self._roleDict then
        self._roleDict = {}
        local confs = GD:queryCosplayConfs()
        for k,v in pairs(confs) do
            local role = CosplayRole.new(v)
            self._roleDict[tonumber(v.ID)] = role
        end
    end
    return self._roleDict[id]
end

-- 更新角色选择状态
function ClassRef:_updateCurRoles()
    -- init roles
    local info1 = self._infos[1]
    local roles = {}
    local roleIds = info1:getRoleIds()
    for i,id in ipairs(roleIds) do
        local role = self:getRoleById(id)
        role:setChooseUid(nil)
        roles[#roles + 1] = role
    end
    self._roles = roles

    local isRepeated = info1:isRepeated()
    for i, info in ipairs(self._infos) do
        -- init role/choice choose status
        local isMyTeam = info:isMyTeam()
        local choices = info:getChoices()
        for i,choice in ipairs(choices) do
            if choice:isChoose() then
                local role = self:getRoleById(choice.rollID)
                if isMyTeam or not isRepeated then
                    role:setChooseUid(choice.uid)
                end
                choice:setRole(role)
            end
        end
    end
end

function ClassRef:S2C_StartRollSelect(msg)
    self._cosType = 1

    if msg.rollplayInfo[1].targetID == Enums.TeamTarget.melee then
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_ARENA_VS,mode = "close"})
    end

    local infos = {}
    for i,v in ipairs(msg.rollplayInfo) do
        local info = CosplayInfo.new()
        info:init(v)
        infos[i] = info
    end
    self._infos = infos
    self:_updateCurRoles()

    app:sendMsg("CosplayController", "openView", self._infos)
end

function ClassRef:S2C_UpdateRollPlayInfo(msg)
    -- dump(msg, "CosplayModel.S2C_UpdateRollPlayInfo", 4)
    if not self._infos then return end
    
    if msg.rollplayInfo.status == "canceled" then
        app:sendMsg("CosplayController", "closeView")
    else
        local upInfo
        for i,info in ipairs(self._infos) do
            info.leftSeconds = msg.rollplayInfo.leftSeconds
            info.status = msg.rollplayInfo.status
            info:refreshInitTime()  --刷新enemyinfo时候主动重置一下initTime
            if info.teamID == msg.rollplayInfo.teamID then
                info:init(msg.rollplayInfo)
                self:_updateCurRoles()
                upInfo = info
            end
        end
        app:sendMsg("CosplayController", "onUpdateSelect", upInfo)
    end
end

-- kof 选角
-- message S2C_StartKOFRollSelect{
--     repeated KOFRollPlayInfo rollplayInfo = 1;
--     repeated int32 roleIDs=2;//当前需要进行抉择的roleids，如果已经完成了抉择，则是最后一次
-- }
function ClassRef:S2C_StartKOFRollSelect(msg)
    -- if true then
    --     self._testKofIDs = {}
    --     local avatarParams1 = UD:getAvatarParams()
    --     avatarParams1.mountID = 0
    --     local avatarParams2 = UD:getAvatarParams()
    --     avatarParams2.uid = 999
    --     avatarParams2.mountID = 0
    --     msg = {
    --         rollplayInfo = {
    --             {
    --                 targetID = 303,
    --                 teamID = "teamID1",
    --                 uid = UD:getUid(),
    --                 userInfo = avatarParams1,
    --                 kofIDs = self._testKofIDs,
    --                 leftSeconds = 30,
    --                 status = "update"
    --             },
    --             {
    --                 targetID = 303,
    --                 teamID = "teamID2",
    --                 uid = 999,
    --                 userInfo = avatarParams2,
    --                 kofIDs = {20106, 20107, 20108},
    --                 leftSeconds = 30,
    --                 status = "update"
    --             }
    --         },
    --         roleIDs = {20101, 20104, 20107}
    --     }
    -- end

    -- dump(msg, "S2C_StartKOFRollSelect", 10)
    self._cosType = 2

    local infos = {}
    for i,v in ipairs(msg.rollplayInfo) do
        local info = CosKOFInfo.new()
        info:init(v)
        if info:isMyTeam() then
            info:setPoolRoles(msg.roleIDs)
        end
        infos[i] = info
    end
    self._kofInfos = infos

    app:sendMsg("CosKOFController", "openView", self._kofInfos)
end

-- kof 选角更新
-- message S2C_UpdateKOFRollSelect{
--     repeated KOFRollPlayInfo rollplayInfo = 1;//需要更新的player信息
--     repeated int32 roleIDs=2;//为空时不更新
-- }
function ClassRef:S2C_UpdateKOFRollSelect(msg)
    if not self._kofInfos then return end

    for i,v in ipairs(msg.rollplayInfo) do
        for _,info in ipairs(self._kofInfos) do
            if info.teamID == v.teamID then
                info:init(v)
                if info:isMyTeam() and msg.roleIDs and #msg.roleIDs > 0 then
                    info:setPoolRoles(msg.roleIDs)
                end

                app:sendMsg("CosKOFController", "onUpdateSelect", info)
                break
            end
        end
    end
end

----------------------------------------- request ------------------------------------
-- 选择角色
-- id = roleId
function ClassRef:reqSelectRole(id)
    -- print("reqSelectRole", id)

    -- for test
    -- table.insert(self._testKofIDs, id)
    -- local param = {
    --     targetID = 303,
    --     teamID = "teamID1",
    --     uid = UD:getUid(),
    --     userInfo = UD:getAvatarParams(),
    --     kofIDs = self._testKofIDs,
    --     leftSeconds = 25,
    --     status = "update"
    -- }
    -- if #param.kofIDs == 3 then
    --     param.status = "finished"
    --     param.leftSeconds = 5
    -- end
    -- local msg = {}
    -- msg.rollplayInfo = {param}
    -- msg.roleIDs = {20101, 20104, 20107}
    -- app:sendMsg("CosKOFController", "onSelectRole")
    -- self:S2C_UpdateKOFRollSelect(msg)
    -- do return end

    if self._isInSelect then return end
    if not self._cosType then return end
    local params = {}
    params.rollID = id

    local infos = self._cosType == 1 and self._infos or self._kofInfos

    for i,info in ipairs(infos) do
        if info:isMyTeam() then
            params.targetID = info.targetID
            params.teamID = info.teamID
            break
        end
    end

    self._isInSelect = true
    app.session:request("pb_rollplay.C2S_SelectRoll", params, function(msg)
        -- dump(msg, "C2S_SelectRoll")
        self._isInSelect = false
    	if msg.OK then
            if self._cosType == 2 then
                app:sendMsg("CosKOFController", "onSelectRole")
            end
            if self._cosType == 1 then
                BattleManager:setTrainingRolePlayId(params.rollID)
            end
    	end
    end, {block = true}, function(errMsg)
        self._isInSelect = false
    end)
end

-- 进入地图loading之后，通知服务器
function ClassRef:reqStartKOF()
    if not self:isKOFMap() then return end
    -- print("reqStartKOF")
    app.session:request("pb_kingofduel.C2S_KingOfDuelFinishEnterGame",{},function(msg)
        -- dump(msg, "C2S_KingOfDuelFinishEnterGame")
    end)
end

return ClassRef